<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="卡名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入卡名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡介绍" prop="introduction">
        <el-input
          v-model="queryParams.introduction"
          placeholder="请输入卡介绍"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['service:cardConfig:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:cardConfig:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:cardConfig:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="cardConfigList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-if="columns[0].visible"
        label="卡名称"
        align="center"
        prop="name"
      />
      <el-table-column
        v-if="columns[1].visible"
        label="卡类型"
        align="center"
        prop="dictType"
      >
        <template slot-scope="scope">
          <dict-tag
            v-if="scope.row.type === '1'"
            :options="dict.type.srv_card_type"
            :value="scope.row.dictType"
          />
          <div v-else-if="scope.row.type === '0'">次卡</div>
          <div v-else>--</div></template
        >
      </el-table-column>
      <el-table-column
        v-if="columns[2].visible"
        label="卡介绍"
        align="center"
        prop="introduction"
      />
      <el-table-column
        v-if="columns[3].visible"
        label="价格"
        align="center"
        prop="price"
      />
      <el-table-column
        v-if="columns[4].visible"
        label="周期(天)"
        align="center"
        prop="period"
      />
      <el-table-column
        v-if="columns[5].visible"
        label="使用次数"
        align="center"
        prop="number"
      />
      <el-table-column
        v-if="columns[6].visible"
        label="积分"
        align="center"
        prop="integration"
      />
      <el-table-column
        v-if="columns[7].visible"
        label="备注"
        align="center"
        prop="remark"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['service:cardConfig:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['service:cardConfig:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员卡配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="卡名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入卡名称" />
        </el-form-item>
        <el-form-item label="是否次卡" prop="type">
          <el-switch
            style="width: 100%"
            v-model="form.type"
            active-value="0"
            inactive-value="1"
            placeholder="请选择是否次卡"
          >
          </el-switch>
        </el-form-item>
        <el-form-item v-if="form.type === '1'" label="卡类型" prop="dictType">
          <el-select
            style="width: 100%"
            v-model="form.dictType"
            placeholder="请选择卡类型"
          >
            <el-option
              v-for="item in dict.type.srv_card_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="carModel">
          <el-select
            style="width: 100%"
            v-model="form.carModel"
            placeholder="请选择车辆类型"
          >
            <el-option
              v-for="dict in dict.type.srv_car_model"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务名称" prop="serveId">
          <el-select
            style="width: 100%"
            v-model="form.serveId"
            placeholder="请选择服务名称"
          >
            <el-option
              v-for="item in serveList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡介绍" prop="introduction">
          <el-input v-model="form.introduction" placeholder="请输入卡介绍" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="周期(天)" prop="period">
          <el-input v-model="form.period" placeholder="请输入周期(天)" />
        </el-form-item>
        <el-form-item label="使用次数" prop="number">
          <el-input v-model="form.number" placeholder="请输入使用次数" />
        </el-form-item>
        <el-form-item label="积分" prop="integration">
          <el-input v-model="form.integration" placeholder="请输入积分" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCardConfig,
  getCardConfig,
  delCardConfig,
  addCardConfig,
  updateCardConfig,
} from "@/api/service/cardConfig";
import { filter, find, join, map, split } from "lodash";
import { listServe } from "@/api/service/serve";

export default {
  name: "CardConfig",
  dicts: ["srv_car_model", "srv_card_type"],
  data() {
    return {
      typeOptions: {
        options: [
          { value: "0", label: "次卡" },
          { value: "1", label: "月卡" },
          { value: "2", label: "季卡" },
          { value: "3", label: "半年卡" },
          { value: "4", label: "年卡" },
        ],
        optionsMap: { 0: "次卡", 1: "月卡", 2: "季卡", 3: "半年卡", 4: "年卡" },
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员卡配置表格数据
      cardConfigList: [],
      // 服务列表
      serveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        introduction: undefined,
      },
      columns: [
        { key: 0, label: `卡名称`, visible: true },
        { key: 1, label: `卡类型`, visible: true },
        { key: 2, label: `卡介绍`, visible: true },
        { key: 3, label: `价格`, visible: true },
        { key: 4, label: `周期（天）`, visible: true },
        { key: 5, label: `使用次数`, visible: true },
        { key: 6, label: `积分`, visible: true },
        { key: 7, label: `备注`, visible: true },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: "卡名称不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "是否次卡不能为空", trigger: "blur" },
        ],
        dictType: [
          { required: true, message: "卡类型不能为空", trigger: "blur" },
        ],
        introduction: [
          { required: true, message: "卡介绍不能为空", trigger: "blur" },
        ],
        price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
        period: [
          { required: true, message: "周期(天)不能为空", trigger: "blur" },
        ],
        number: [
          { required: true, message: "使用次数不能为空", trigger: "blur" },
        ],
        delayNumber: [
          { required: true, message: "延期次数不能为空", trigger: "blur" },
        ],
        serveId: [
          { required: true, message: "服务名称不能为空", trigger: "change" },
        ],
        carModel: [
          { required: true, message: "车辆类型不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getServeList();
    this.getList();
  },
  methods: {
    // 服务列表
    getServeList() {
      listServe({ pageNum: 1, pageSize: 999999 }).then((response) => {
        this.serveList = map(response.rows, (v) => ({
          label: v?.serveName,
          value: v?.id,
        }));
      });
    },
    /** 查询会员卡配置列表 */
    getList() {
      this.loading = true;
      listCardConfig(this.queryParams).then((response) => {
        this.cardConfigList = map(response.rows, (v) => ({
          ...v,
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        introduction: undefined,
        price: undefined,
        period: undefined,
        type: "0",
        number: undefined,
        delayNumber: undefined,
        serveId: undefined,
        serveName: undefined,
        carModel: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        delFlag: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员卡配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getCardConfig(id).then((response) => {
        this.loading = false;
        this.form = {
          ...response.data,
          serveId: response?.data?.serveId, //filter(split(response?.data?.serveId, ",")),
        };
        this.open = true;
        this.title = "修改会员卡配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          const result = {
            ...this.form,
            // serveId: join(this.form.serveId, ","),
            serveName: find(this.serveList, { value: this.form.serveId })
              ?.label,
          };
          if (this.form.id != null) {
            updateCardConfig(result)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addCardConfig(result)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除会员卡配置编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delCardConfig(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "service/cardConfig/export",
        {
          ...this.queryParams,
        },
        `cardConfig_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
